<?php
// +----------------------------------------------------------------------
// | FastXCMS [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2018 http://www.fastxcms.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 老猫 <thinkcmf@126.com>
// +----------------------------------------------------------------------
namespace app\portal\model;

use app\admin\model\RouteModel;
use think\Model;
use tree\Tree;

class PortalCategoryModel extends Model
{

    protected $type = [
        'more' => 'array',
    ];

    /**
     * 生成分类 select树形结构
     * @param int $selectId 需要选中的分类 id
     * @param int $currentCid 需要隐藏的分类 id
     * @return string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function adminCategoryTree($selectId = 0, $currentCid = 0, $moduleCid = 0)
    {
		global $configinfo;
		
        $where = ['delete_time' => 0];
        if (!empty($currentCid)) {
            $where['id'][] = ['neq', $currentCid];
        }
		if(!empty($configinfo['colids']))$where['id'][] = ['notin', $configinfo['colids']];// 关闭一级菜单
		if(!empty($configinfo['colids2']))$where['id'][] = ['notin', $configinfo['colids2']];// 关闭二级菜单
		if(!empty($configinfo['colids3']))$where['id'][] = ['notin', $configinfo['colids3']];// 关闭三级菜单
		// 系统配置仅限总管理员访问
		if($configinfo['adminid'] > 1)
		{
			$where['id'][] = ['neq', 11];
			$where['id'][] = ['neq', 14];
			$where['editqx'] = ['eq', 0];
			$where['index_num'] = ['neq', '自定义扩展'];
		}
        $categories = $this->order("list_order ASC")->where($where)->select()->toArray();

        $tree       = new Tree();
        $tree->icon = ['&nbsp;&nbsp;│', '&nbsp;&nbsp;├─', '&nbsp;&nbsp;└─'];
        $tree->nbsp = '&nbsp;&nbsp;';

        $newCategories = [];
        foreach ($categories as $item) {
            $item['selected'] = $selectId == $item['id'] ? "selected" : "";

            array_push($newCategories, $item);
        }

        $tree->init($newCategories);
        $str     = '<option value=\"{$id}\" {$selected}>|--{$spacer}{$name}</option>';
        $treeStr = $tree->getTree($moduleCid, $str);

        return $treeStr;
    }

    /**
     * 分类树形结构
     * @param int $currentIds
     * @param string $tpl
     * @return string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function adminCategoryTableTree($currentIds = 0, $tpl = '', $moduleCid = 0)
    {
		global $configinfo;
		
        $where = ['delete_time' => 0];
		if (!empty($moduleCid)) {
			$parentclassarr = getparentclassall($moduleCid);
			$parentclassids = getarrtostr(",",$parentclassarr);
			$category = getbottomclass($configinfo["ecs_article_cat"],$moduleCid,$configinfo['cat_id'],$configinfo['parent_id'],1);
			if($parentclassids)$category.=",".$parentclassids;
            $where['id'][] = ['in', $category];
        }
//        if (!empty($currentCid)) {
//            $where['id'] = ['neq', $currentCid];
//        }
		if(!empty($configinfo['colids']))$where['id'][] = ['notin', $configinfo['colids']];// 关闭一级菜单
		if(!empty($configinfo['colids2']))$where['id'][] = ['notin', $configinfo['colids2']];// 关闭二级菜单
		if(!empty($configinfo['colids3']))$where['id'][] = ['notin', $configinfo['colids3']];// 关闭三级菜单
		// 系统配置仅限总管理员访问
		if($configinfo['adminid'] > 1)
		{
			$where['id'][] = ['neq', 11];
			$where['id'][] = ['neq', 14];
			$where['editqx'] = ['eq', 0];
			$where['index_num'] = ['neq', '自定义扩展'];
		}
        $categories = $this->order("list_order ASC")->where($where)->select()->toArray();

        $tree       = new Tree();
        $tree->icon = ['&nbsp;&nbsp;│', '&nbsp;&nbsp;├─', '&nbsp;&nbsp;└─'];
        $tree->nbsp = '&nbsp;&nbsp;';

        if (!is_array($currentIds)) {
            $currentIds = [$currentIds];
        }

        $newCategories = [];
        foreach ($categories as $item) {
            $item['parent_id_node'] = ($item['parent_id']) ? ' class="child-of-node-' . $item['parent_id'] . '"' : '';
            $item['style']          = empty($item['parent_id']) ? '' : 'display:none;';
			$item['bannerhtml']          = empty($item['more']['bannerimg']) ? '<img src="/themes/admin_simpleboot3/public/assets/images/default-thumbnail.png" width="60" height="60" />' : '<img src="'.cmf_get_image_preview_url($item['more']['bannerimg']).'" width="60" height="60" />';
            $item['systemok_text'] = $item['systemok'] == 1 ? '<span class="label label-danger">系统栏目</span>' : ($item['systemok'] == 2 ? '<span class="label label-success">模板栏目</span>' : '<span class="label label-primary">普通栏目</span>');
			if($configinfo['recok'] == 1)$item['recok_text'] = $item['recok'] == 1 ? '<td><span class="label label-info">是</span></td>' : '<td><span class="label label-warning">否</span></td>';
			$item['status_text']    = empty($item['status'])?'<span class="label label-danger">隐藏</span>':'<span class="label label-success">显示</span>';
            $item['checked']        = in_array($item['id'], $currentIds) ? "checked" : "";
            $item['url']            = cmf_url('portal/List/index', ['id' => $item['id']]);
			
			// 获取当前分类模块信息
			$topid = $item['moduleid'];
			$topinfo = $this->where('id', $topid)->find();
			$moduletopid = $item['moduletopid'];
			$moduletopinfo = $this->where('id', $moduletopid)->find();
			
			// 添加子分类
			if(($topinfo['index_num'] != '自定义插件' && $topinfo['index_num'] != '自定义单页' && $topinfo['addqx'] == 0) || $configinfo['adminid'] == 1)
			{
				$item['str_action'] = '<a style="display:inline-block;" href="' . url("AdminCategory/add", ["category" => $item['id'], "parent" => $item['id']]) . '">添加子分类</a>&nbsp;|&nbsp;';
			}
			
			// 查看下级
			$item['str_action'] .= '<a style="display:inline-block;" href="' . url("AdminCategory/index", ["category" => $item['id'], "backOk" => 1]) . '">查看下级</a>&nbsp;|&nbsp;';
			
			// 编辑分类
			if(iszdyblockconfig($moduletopid,0,$moduletopid) == 2 || $configinfo['adminid'] == 1)
			{
				$moduleCategory = $moduleCid ? $moduleCid : $item['moduletopid'];
				$item['str_action'] .= '<a style="display:inline-block;" href="' . url("AdminCategory/edit", ["id" => $item['id'], "category" => $moduleCategory]) . '">' . lang('EDIT') . '分类</a>&nbsp;|&nbsp;';
			}
			
			// 删除分类
			if($item['parent_id'] > 0 && $item['systemok'] == 0)
			{
				$item['str_action'] .= '<a style="display:inline-block;" class="js-ajax-delete" href="' . url("AdminCategory/delete", ["id" => $item['id']]) . '">' . lang('DELETE') . '分类</a>&nbsp;|&nbsp;';
			}
			
			// 隐藏显示分类
			if(iszdyblockconfig($moduletopid,1,$moduletopid)['zdyok'] == 0)
			{
				if ($item['status']) {
					$item['str_action'] .= '<a style="display:inline-block;" class="js-ajax-dialog-btn" data-msg="您确定隐藏此分类吗" href="' . url('AdminCategory/toggle', ['ids' => $item['id'], 'hide' => 1]) . '">隐藏分类</a>&nbsp;|&nbsp;';
				} else {
					$item['str_action'] .= '<a style="display:inline-block;" class="js-ajax-dialog-btn" data-msg="您确定显示此分类吗" href="' . url('AdminCategory/toggle', ['ids' => $item['id'], 'display' => 1]) . '">显示分类</a>&nbsp;|&nbsp;';
				}
			}
			
			// 数据列表
			if($topinfo['index_num'] != '自定义分类')
			{
				$item['str_action'] .= '<a style="display:inline-block;" href="' . url("AdminArticle/index", ["category" => $item['id'], "backOk" => 1]) . '">数据列表</a>&nbsp;|&nbsp;';
			}
			
			// 获取模块公用开启配置
			$topmodule_moduleconfig = gettopmodule($topid,"moduleconfig");
			$itemcolumn_moduleconfig = gettopmodule($item['id'],"moduleconfig");
			
			// 栏目参数
			if($configinfo['zdypara'] == 1)
			{
				if($topmodule_moduleconfig['columnparaok'] == 1)
				{
					$item['str_action'] .= '<a style="display:inline-block;" href="' . url("AdminArticle/index", ["category" => 73, "attrid" => $item['id'], "backOk" => 1]) . '">栏目参数</a>&nbsp;|&nbsp;';
				}
			}
			// 订购参数
			if($configinfo['shopok'] == 1)
			{
				if($topmodule_moduleconfig['shopparaok'] == 1)
				{
					$item['str_action'] .= '<a style="display:inline-block;" href="' . url("AdminArticle/index", ["category" => 106, "attrid" => $item['id'], "backOk" => 1]) . '">订购参数</a>&nbsp;|&nbsp;';
				}
			}
			// TAG标签
			if($configinfo['tagok'] == 1 && $itemcolumn_moduleconfig['tagok'] == 1)
			{
				$item['str_action'] .= '<a style="display:inline-block;" href="' . url("AdminTag/index", ["category" => $item['id'], "backOk" => 1]) . '">TAG标签</a>&nbsp;|&nbsp;';
			}
			// 评论管理
			if($configinfo['commentok'] == 1 && $itemcolumn_moduleconfig['commentok'] == 1)
			{
				$item['str_action'] .= '<a style="display:inline-block;" href="/plugin/comment/admin_index/index.html?commentmoduleid='.$item['id'].'&backOk=1">评论管理</a>&nbsp;|&nbsp;';
			}
			
            array_push($newCategories, $item);
        }

        $tree->init($newCategories);

        if (empty($tpl)) {
            $tpl = " <tr id='node-\$id' \$parent_id_node style='\$style' data-parent_id='\$parent_id' data-id='\$id'>
                        <td style='padding-left:20px;'><input type='checkbox' class='js-check' data-yid='js-check-y' data-xid='js-check-x' name='ids[]' value='\$id' data-parent_id='\$parent_id' data-id='\$id'></td>
						<td>\$id</td>
                        <td><input name='list_orders[\$id]' type='text' size='3' value='\$list_order' class='input-order'></td>
                        <td>\$spacer <a href='\$url' target='_blank'>\$name</a></td>
						<td>\$bannerhtml</td>
						<td>\$systemok_text</td>
                        \$recok_text
						<td>\$status_text</td>
                        <td>\$str_action</td>
                    </tr>";
        }
        $treeStr = $tree->getTree(0, $tpl);

        return $treeStr;
    }

    /**
     * 添加文章分类
     * @param $data
     * @return bool
     */
    public function addCategory($data)
    {
		global $configinfo;
		
        $result = true;
        self::startTrans();
        try {
            if (!empty($data['more']['thumbnail'])) {
                $data['more']['thumbnail'] = cmf_asset_relative_url($data['more']['thumbnail']);
            }
			if (!empty($data['more']['bannerimg'])) {
                $data['more']['bannerimg'] = cmf_asset_relative_url($data['more']['bannerimg']);
            }
            $this->allowField(true)->save($data);
            $id = $this->id;
			
            if (empty($data['parent_id'])) {
				
				// 配置模块ID
				$moduleID = gettopclass($configinfo["ecs_article_cat"], $id, $configinfo["cat_id"], $configinfo["parent_id"]);
				
				// 配置模块顶级ID
				$moduleTopID = $id;

                $this->where(['id' => $id])->update(['path' => '0-' . $id, 'classtype' => 1, 'moduleid' => $moduleID, 'moduletopid' => $moduleTopID]);
            } else {
                $parentPath = $this->where('id', intval($data['parent_id']))->value('path');
				
				// 统计当前分类层级
				$parentPatharr = getstrtoarr("-","$parentPath-$id");
				$classtypecount = count($parentPatharr)-1;
				
				$opClassID = $id;
				// 当分类层级大于三级时只获取三级分类
				if($classtypecount > 3)
				{
					$opclassid = $parentPatharr[3];
				}
				
				// 配置模块ID
				$moduleID = gettopclass($configinfo["ecs_article_cat"], $opclassid, $configinfo["cat_id"], $configinfo["parent_id"]);
				
				// 配置模块顶级ID
				$moduleTopID = $parentPatharr[1];
				
                $this->where(['id' => $id])->update(['path' => "$parentPath-$id", 'classtype' => $classtypecount, 'moduleid' => $moduleID, 'moduletopid' => $moduleTopID]);

            }
            self::commit();
        } catch (\Exception $e) {
            self::rollback();
            $result = false;
        }

        if ($result != false) {
            //设置URL静态名
            $routeModel = new RouteModel();
            if (!empty($data['alias']) && !empty($id)) {
				
				// ----------------多语言配置START
				global $configinfo;
				if($configinfo['langok'])
				{
					$routeModel->setRoute($data['alias'] . '-&lt;lang&gt;', 'portal/List/index', ['id' => $id], 2, 5000);
                	$routeModel->setRoute($data['alias'] . '/&lt;id&gt;-&lt;lang&gt;', 'portal/Article/index', ['cid' => $id], 2, 4999);
				}else{
					$routeModel->setRoute($data['alias'], 'portal/List/index', ['id' => $id], 2, 5000);
                	$routeModel->setRoute($data['alias'] . '/:id', 'portal/Article/index', ['cid' => $id], 2, 4999);
				}
				// ----------------多语言配置END
				
            }
            $routeModel->getRoutes(true);
        }

        return $result;
    }

    public function editCategory($data)
    {
		global $configinfo;
		
        $result = true;

        $id          = intval($data['id']);
        $parentId    = intval($data['parent_id']);
        $oldCategory = $this->where('id', $id)->find();

        if (empty($parentId)) {
            $newPath = '0-' . $id;
        } else {
            $parentPath = $this->where('id', intval($data['parent_id']))->value('path');
            if ($parentPath === false) {
                $newPath = false;
            } else {
                $newPath = "$parentPath-$id";
            }
        }

        if (empty($oldCategory) || empty($newPath)) {
            $result = false;
        } else {

            $data['path'] = $newPath;
			
			// 统计当前分类层级
			$newPatharr = getstrtoarr("-",$newPath);
			$classtypecount = count($newPatharr)-1;
			$data['classtype'] = $classtypecount;
			
			$opClassID = $id;
			// 当分类层级大于三级时只获取三级分类
			if($classtypecount > 3)
			{
				$opclassid = $newPatharr[3];
			}
			
			// 配置模块ID
			$data['moduleid'] = gettopclass($configinfo["ecs_article_cat"], $opClassID, $configinfo["cat_id"], $configinfo["parent_id"]);
			
			// 配置模块顶级ID
			$data['moduletopid'] = $newPatharr[1];
			
            if (!empty($data['more']['thumbnail'])) {
                $data['more']['thumbnail'] = cmf_asset_relative_url($data['more']['thumbnail']);
            }
			if (!empty($data['more']['bannerimg'])) {
                $data['more']['bannerimg'] = cmf_asset_relative_url($data['more']['bannerimg']);
            }
            $this->isUpdate(true)->allowField(true)->save($data, ['id' => $id]);

            $children = $this->field('id,path')->where('path', 'like', $oldCategory['path'] . "-%")->select();
            if (!$children->isEmpty()) {
                foreach ($children as $child) {
                    $childPath = str_replace($oldCategory['path'] . '-', $newPath . '-', $child['path']);
					
					// 统计当前分类层级
					$childPatharr = getstrtoarr("-",$childPath);
					$childclasstypecount = count($childPatharr)-1;
					
					$opChildClassID = $child['id'];
					// 当分类层级大于三级时只获取三级分类
					if($childclasstypecount > 3)
					{
						$opChildClassID = $childPatharr[3];
					}
					
					// 配置模块ID
					$childModuleID = gettopclass($configinfo["ecs_article_cat"], $opChildClassID, $configinfo["cat_id"], $configinfo["parent_id"]);
					
					// 配置模块顶级ID
					$childModuleTopID = $childPatharr[1];
					
                    $this->where('id', $child['id'])->update(['path' => $childPath, 'classtype' => $childclasstypecount, 'moduleid' => $childModuleID, 'moduletopid' => $childModuleTopID], ['id' => $child['id']]);
                }
            }

            $routeModel = new RouteModel();
			
			if (!empty($data['alias'])) {
				
				// ----------------多语言配置START
				global $configinfo;
				if($configinfo['langok'])
				{
					$routeModel->setRoute($data['alias'] . '-&lt;lang&gt;', 'portal/List/index', ['id' => $data['id']], 2, 5000);
					$routeModel->setRoute($data['alias'] . '/&lt;id&gt;-&lt;lang&gt;', 'portal/Article/index', ['cid' => $data['id']], 2, 4999);
				}else{
					$routeModel->setRoute($data['alias'], 'portal/List/index', ['id' => $data['id']], 2, 5000);
					$routeModel->setRoute($data['alias'] . '/:id', 'portal/Article/index', ['cid' => $data['id']], 2, 4999);
				}
				// ----------------多语言配置END
				
			} else {
				$routeModel->deleteRoute('portal/List/index', ['id' => $data['id']]);
				$routeModel->deleteRoute('portal/Article/index', ['cid' => $data['id']]);
			}

            $routeModel->getRoutes(true);
        }


        return $result;
    }


}